package com.fin.zw.aiqas.service;

import com.fin.zw.aiqas.entity.FormulaInfo;
import com.fin.zw.aiqas.entity.Keyword;
import com.fin.zw.aiqas.entity.UploadFile;
import com.fin.zw.aiqas.repository.KeywordRepository;
import com.fin.zw.aiqas.util.CSVUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ImportService {

    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    private FormulaService formulaService;
    @Autowired
    private KeywordRepository keywordRepository;


    public void importKeyWord(MultipartFile multFile) throws Exception {
        ResponseEntity<UploadFile> uploadFileResponseEntity = uploadFileService.fileUpload(multFile);
        UploadFile body = uploadFileResponseEntity.getBody();
        File file = uploadFileService.findOneFileById(Long.valueOf(body.getId()));
        Map<String, List<String>> maps = CSVUtils.readCSV(file);
        List<String> head = maps.get("head");
        List<String> data = maps.get("data");
        FormulaInfo formula = formulaService.getFormula(head.get(0));
//      是否同步的状态现未确定是否修改
        List<Keyword> keywords = new ArrayList<>();
        for (String datum : data) {
            Keyword keyword = new Keyword();
            keyword.setKeyword_info_id(formula.getId());
            keyword.setName(datum);
            keywords.add(keyword);
        }
        keywordRepository.saveAll(keywords);
    }
}
